import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router';
import { reduxForm } from 'redux-form';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button, ControlLabel, FormControl, FormGroup, HelpBlock } from 'react-bootstrap';
import { notify } from 'react-notify-toast';

const brand = require('../../assets/images/brand.png');
const $ = require('$');
const qs = require('qs');

const { API_BASENAME } = process.env;

import * as ProjectActions from 'redux/actions/ProjectActions';
import * as SessionActions from 'redux/actions/SessionActions';

const validate = (values, props) => {
  const errors = {};
  if (!values.email) {
    errors.email = '账号不能为空';
  }

  if (!values.password) {
    errors.password = '密码不能为空';
  }

  if (props.session.captchaRequired && !values.captcha) {
    errors.captcha = '验证码不能为空';
  }
  return errors;
};

function mapStateToProps(state) {
  return {
    session: state.session
  };
}

function mapDispatchToProps(dispatch) {
  return {
    projectActions: bindActionCreators(ProjectActions, dispatch),
    actions: bindActionCreators(SessionActions, dispatch)
  };
}

@connect(mapStateToProps, mapDispatchToProps)
@reduxForm({
  form: 'login',
  fields: ['email', 'password', 'captcha'],
  validate
})
class Login extends Component {
  constructor(props) {
    super(props);
    this.random = this.randomString(10);
    this.captchaImgUrl = API_BASENAME + '/captcha?random=' + this.random;
    this.state = { alertShow: false, captchaImgUrl: this.captchaImgUrl };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.hideAlert = this.hideAlert.bind(this);
    this.refreshCaptcha = this.refreshCaptcha.bind(this);
  }

  static contextTypes = {
    router: PropTypes.object.isRequired
  }

  static propTypes = {
    location: PropTypes.object.isRequired,
    session: PropTypes.object.isRequired,
    projectActions: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired,
    submitting: PropTypes.bool,
    handleSubmit: PropTypes.func.isRequired,
    invalid: PropTypes.bool,
    fields: PropTypes.object,
    values: PropTypes.object
  }

  async componentWillMount() {
    const { actions, session, projectActions } = this.props;
    if (!session.invalid) {
      await actions.getSess();
      $('#main-loading').css({ 'width': '0px', 'height': '0px', 'background': 'none', 'display': 'none' });
      $('#main-loading img').css({ 'display': 'none' });
      const { session } = this.props;
      if (session.ecode === 0 && session.user.id) {
        if (session.user.email === 'admin@action.view') {
          this.context.router.push({ pathname: '/admin/scheme/type' });
        } else {
          projectActions.cleanSelectedProject();
          if (session.user.latest_access_project) {
            this.context.router.push({ pathname: '/project/' + session.user.latest_access_project + '/summary' });
          } else {
            this.context.router.push({ pathname: '/myproject' });
          }
        }  
      }
    }
  }

  componentDidMount() {
    $('input[name=email]').attr('autocomplete', 'Off');
    $('input[name=password]').attr('autocomplete', 'Off');

    const self = this;
    $('input[name=email]').bind('keypress', function() {
      self.hideAlert();
    });
    $('input[name=password]').bind('keypress', function() {
      self.hideAlert();
    });
  }

  hideAlert() {
    this.setState({ alertShow: false });
  }

  async handleSubmit() {
    this.setState({ alertShow: false });

    const { 
      location: { query={} },
      session: { captchaRequired=false },
      values, 
      actions, 
      projectActions 
    } = this.props;

    const data = {};
    data.email = values.email || '';
    data.password = values.password || '';

    if (captchaRequired) {
      data.captcha = values.captcha || '';
      data.random = this.random || '';
    }

    await actions.create(data);

    const { session } = this.props;
    if (session.ecode === 0 && session.user && session.user.id) {
      if (!session.user.directory && values.password == 'actionview') {
        notify.show('登录密码是初始密码，为保证安全请尽快修改。', 'warning', 3000);
      }
      if (query.request_url) {
        let requests = decodeURI(query.request_url).split('?');
        let pathname = requests.shift();
        let query2 = {};
        if (requests.length > 0) {
          query2 = qs.parse(requests.shift());
        }
        this.context.router.push({ pathname, query: query2 });    
      } else {
        if (session.user.email === 'admin@action.view') {
          this.context.router.push({ pathname: '/admin/scheme/type' });
        } else {
          projectActions.cleanSelectedProject();
          if (session.user && session.user.latest_access_project) {
            this.context.router.push({ pathname: '/project/' + session.user.latest_access_project + '/summary' });
          } else {
            this.context.router.push({ pathname: '/myproject' });    
          }
        }
      }
    } else {
      this.setState({ alertShow: true });
      session.captchaRequired && data.captcha && this.refreshCaptcha();
    }
  }

  refreshCaptcha() {
    const { fields: { captcha } } = this.props;
    captcha.onChange('');

    this.setState({ captchaImgUrl: this.captchaImgUrl + '&reqeusted_at=' + Date.now() })
  }

  randomString(length) {  
    const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (var i = length; i > 0; --i) { 
      result += str[Math.floor(Math.random() * str.length)];
    }
    return result;
  }

  render() {
    const { 
      fields: { email, password, captcha }, 
      handleSubmit, 
      invalid, 
      submitting, 
      session 
    } = this.props;

    const errMsgs = {
      '-10000': '登录失败，用户名或密码错误。',
      '-10005': '用户未激活。',
      '-10006': '用户已被禁用。',
      '-10007': '请输入验证码。',
      '-10008': '验证码错误。',
      '-10009': '验证码失效。'
    };

    return (
      <div className='login-panel'>
        <div className='login-form'>
          <div className='brand'>
            <img src={ brand } width={ 200 }/>
          </div>
          <form onSubmit={ handleSubmit(this.handleSubmit) }>
            <FormGroup validationState={ email.touched && email.error ? 'error' : null }>
              <FormControl disabled={ submitting } type='text' { ...email } placeholder='用户名/邮箱'/>
              { email.touched && email.error && <HelpBlock style={ { marginLeft: '5px' } }>{ email.error }</HelpBlock> }
            </FormGroup>
            <FormGroup validationState={ password.touched && password.error ? 'error' : null }>
              <FormControl disabled={ submitting } type='password' { ...password } placeholder='密码'/>
              { password.touched && password.error && <HelpBlock style={ { marginLeft: '5px' } }>{ password.error }</HelpBlock> }
            </FormGroup>
            { session.captchaRequired &&
              <FormGroup>
                <FormControl disabled={ submitting } type='text' { ...captcha } placeholder='验证码' style={ { width: '200px', display: 'inline-block' } }/>
                <img src={ this.state.captchaImgUrl } onClick={ this.refreshCaptcha } style={ { width: '100px', marginLeft: '20px' } }/>
              </FormGroup> }
            <Button bsStyle='success' disabled={ submitting } type='submit'>
              { submitting ? '登 录 中 ...' : '登 录' }
            </Button>
            <div style={ { textAlign: 'center', height: '40px' } }>
              { this.state.alertShow && !submitting && session.ecode !== 0 &&  
                <div style={ { marginTop: '10px', color: '#a94442' } }>
                  { errMsgs[session.ecode] || '系统错误。' }
                </div> }
            </div>
            <div className='login-footer'>
              <span>若非该系统用户，请联系系统管理员创建。</span>
              <Link to='/forgot' style={ { marginLeft: '5px' } }>忘记密码</Link>
              {/*<span className='split'/>
              <Link to='/register'>用户注册</Link> */}
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Login;
